// $.getScript("/Portal/test/js/khjd.js");

$(function () {

    //用于debugger alert()
    var originAlert = window.alert; // 首先记录原生的alert
    window.alert = function (text) { // 用我们带断点的alert覆盖window.alert
        // debugger;
        return originAlert.call(window, text);
    };

    console.log("开始加载自定义。。。。");
    $(".myblock").css({
        "padding-bottom": "15px"
    })
    $(".mylabel").css({
        "font-weight": "bold",
        "font-size": "13px",
        "border-bottom": "2px solid #ccc",
        "height": "22px",
        "width": "100%",
        "margin-left":"-15px",
        "margin-right":"-15px"
    });

    // 模块标签点击
    $(".mylabel").click(function () {

        var that = $(this);
        var fa_right = "fa fa-chevron-right";
        var fa_down = "fa fa-chevron-down";
        var $next = that.next();
        //展开
        if (that.hasClass(fa_right)) {
            that.removeClass(fa_right);
            that.addClass(fa_down);
            $next.hide();
            console.log("go r");
        } else {
            that.removeClass(fa_down);
            that.addClass(fa_right);
            $next.show();
            // console.log("go l");
        }
        return false;
    });


    //初始化js
    if (window.addEventListener) {
        window.addEventListener("load", csh, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", csh);
    } else {
        window.onload = csh;
    }


});

//初始化
function csh() {
    try {

        //添加一个地址
        activeAdds();
        //币别
        // curChange();
        // 初始化子表地址编码 dropdownlist 映射
        dizi_drop_list();
        // 设置语言
        setLanguage();
        //销售代表
        queryXsdb();
        //地址编码
        // bpaddressInit();

        //默认收获地址
        checboxOnlyDefshflgInit();

        inputKeypress();

    }catch (e) {
        console.log(e);
    }



}


function ytruetim() {

    if($.MvcSheetUI.SheetInfo.ActivityCode=='Activity8'){

        var time =$.MvcSheetUI.GetControlValue("OriginateTime");
        if(!time){
            time = (time ? time : new Date());
            $.MvcSheetUI.SetControlValue("YTRUETIM",time);
        }
    }

}



//付款条件编码：现金交易
var xjbm = "00001";

//提交时表单验证的可变数据
var thisValidData = [];


// 收获地址默认控制
function checboxOnlyDefshflg($this) {

    var rowIndex = $this.parents("tr").data("row");
    var thisvals = $this.SheetComment().GetValue();
    var rowField = $this.SheetComment().DataField;
    var tbField = rowField.split('.')[0];
    var rowSibField = rowField.substr(0, rowField.indexOf("_XS"));
    var rowcount = $.MvcSheetUI.GetElement(tbField).SheetGridView().RowCount;

    if (!thisvals && rowcount > 0) {
        for (var i = 1; i < rowcount + 1; i++) {
            var shflg = $.MvcSheetUI.GetControlValue("BPADDRESSCHG.YSHFLG_XS", i);
            if (shflg) {
                $.MvcSheetUI.SetControlValue(rowField, true, i);
                $.MvcSheetUI.SetControlValue(rowSibField, 2, i);
                break;
            }
        }
        return false;
    }

    for (var i = 1; i < rowcount + 1; i++) {
        // debugger;
        if (rowIndex != i) {
            $.MvcSheetUI.SetControlValue(rowField, false, i);
            $.MvcSheetUI.SetControlValue(rowSibField, 1, i);
        }else{
            $.MvcSheetUI.SetControlValue(rowSibField, 2, i);
        }
    }
}

function checboxOnlyDefshflgInit() {

    var tb = $.MvcSheetUI.GetElement("BPADDRESSCHG").SheetGridView();
    var rowcount = tb.RowCount;

    for (var i = 1; i < rowcount + 1; i++) {
        // debugger;
        if ($.MvcSheetUI.GetControlValue("BPADDRESSCHG.YSHFLG_XS", i)) {
            $.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG_XS", i).removeAttr("disabled");
        }
    }

}


function checboxOnly($this) {

    var rowIndex = $this.parents("tr").data("row");
    var thisvals = $this.SheetComment().GetValue();
    var rowField = $this.SheetComment().DataField;
    var tbField = rowField.split('.')[0];
    var rowSibField = rowField.substr(0, rowField.indexOf("_XS"));

    var rowcount = $.MvcSheetUI.GetElement(tbField).SheetGridView().RowCount;


    if (!thisvals && rowcount > 0) {
        $.MvcSheetUI.GetElement(rowField, 1).SheetComment().SetValue(true);
        $.MvcSheetUI.GetElement(rowSibField, 1).SheetComment().SetValue(2);

        return false;
    }

    for (var i = 1; i < rowcount + 1; i++) {
        // debugger;
        if (rowIndex != i) {

            $.MvcSheetUI.GetElement(rowField, i).SheetComment().SetValue(false);
            $.MvcSheetUI.GetElement(rowSibField, i).SheetComment().SetValue(1);
        }else{
            $.MvcSheetUI.GetElement(rowSibField, i).SheetComment().SetValue(2);
        }
    }
}

//是否收获地址 chcekbox
function isReceivingAdd_Chcekbox($this) {
    var vals = $this.SheetComment().GetValue();
    var rowIndex = $this.parents("tr").data("row");
    //是否默认收货地点
    var $daulRecei = $.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG_XS", rowIndex);

    var $sib = $.MvcSheetUI.GetElement($this.SheetComment().DataField.substr(0, $this.SheetComment().DataField.indexOf("_XS")), rowIndex);
    // 1否2是，是收获地址
    if (vals) {
        //设置为是并解除 disable
        $daulRecei.SheetComment().SetValue(2);
        $daulRecei.removeAttr("disabled");
        $daulRecei.change();

        $sib.SheetComment().SetValue(2);
    } else {
        //设置为否和disable
        $daulRecei.SheetComment().SetValue(1);
        $daulRecei.attr("disabled", "disabled");
        $sib.SheetComment().SetValue(1);

        checboxOnlyDefshflg($daulRecei);

    }
}


//是否收获地址 raido 类型的--不用了
function isReceivingAdd($this) {
    var vals = $this.SheetComment().GetValue();
    var rowIndex = $this.parents("tr").data("row");
    //是否默认收货地点
    var $daulRecei = $.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG", rowIndex);
    //装运地
    var $stofcy = $.MvcSheetUI.GetElement("BPADDRESSCHG.STOFCY_XS", rowIndex);

    // 1否2是，是收获地址
    if (vals && vals == 2) {
        //设置为是并解除 disable
        $daulRecei.SheetRadioButtonList().SetValue(2);
        $daulRecei.removeAttr("disabled");
        $daulRecei.change();
        // 装运地必填
        $stofcy.SheetComment().Required = true;
        if (!$stofcy.SheetComment().GetValue())
            $stofcy.SheetComment().AddInvalidText($stofcy, "*", false);
        $stofcy.blur(function () {
            var $thisblur = $(this);
            if ($thisblur.SheetComment().GetValue()) {
                $thisblur.SheetComment().RemoveInvalidText($thisblur);
            } else {
                $thisblur.SheetComment().AddInvalidText($thisblur, "*", true);
            }
        })

    } else {
        //设置为否和disable
        $daulRecei.SheetRadioButtonList().SetValue(1);
        $daulRecei.attr("disabled", "disabled");
        // 装运地非必填
        $stofcy.SheetComment().Required = true;
        $stofcy.SheetComment().RemoveInvalidText($stofcy);
    }
}

//子表 多行默认行唯一  ---不用了
function sublist_only_one($this, gridViewBm, gridDataBm) {

    var gridView = $.MvcSheetUI.GetElement(gridViewBm).SheetGridView();
    var thisIndex = $this.parents("tr").data("row");

    var thisvals = $.MvcSheetUI.GetElement(gridDataBm, thisIndex).SheetRadioButtonList().GetValue();
    // 值的改变才会触发，当值为1 的时候，说明从2变成1，设置第一行为默认值
    if (thisvals == 1) {
        // $.MvcSheetUI.GetElement(gridDataBm, 1).SheetRadioButtonList().SetValue(2);
        return false;
    }

    var rowCount = gridView.RowCount;
    for (var i = 1; i < rowCount + 1; i++) {
        // debugger;
        $.MvcSheetUI.GetElement(gridDataBm, i).SheetRadioButtonList().SetValue(1);
    }

    $.MvcSheetUI.GetElement(gridDataBm, thisIndex).SheetRadioButtonList().SetValue(2);

}

//地址编码联动
function dizi_drop_list() {
    var di = "BPADDRESSCHG";//客户地址子表
    var dibm = "BPADDRESSCHG.BPAADD";//地址行编码

    var gridView = $.MvcSheetUI.GetElement(di).SheetGridView();

    var rowCount = gridView.RowCount;
    var defaultItems = "";
    for (var i = 1; i < rowCount + 1; i++) {
        defaultItems += $.MvcSheetUI.GetElement(dibm, i).SheetTextBox().GetValue();
        if (rowCount != i) {
            defaultItems += ";";
        }
    }
    di = "CONTACTCHG";//地址联系人子表
    dibm = "CONTACTCHG.BPAADD";//地址联系人行编码

    //给 地址联系人子表 的地址编码 SheetDropDownList 赋 默认值
    renderDefaultItems(di, dibm, defaultItems);
}

//重新渲染子表赋值
function renderDefaultItems(di, dibm, defaultItems) {
    var gridView = $.MvcSheetUI.GetElement(di).SheetGridView();
    var templates = gridView.template;
    if (!templates){
        return false;
    }
    var templateSelect = templates.find("td>select[data-field='" + dibm + "']");
    if (templateSelect.data("defaultItems") != defaultItems) {
        var rowCount = gridView.RowCount;
        //设置 子表 template 里的 SheetDropDownList  defaultItems
        templateSelect.attr("data-defaultItems", defaultItems);

        for (var i = 1; i < rowCount + 1; i++) {
            var vals = $.MvcSheetUI.GetControlValue(dibm, i);
            vals = vals ? vals : $.MvcSheetUI.GetSheetDataItem(dibm, i);
            var $UIManager = $.MvcSheetUI.GetElement(dibm, i).SheetUIManager();
            $UIManager.SetEmpty();//清空原数据
            $UIManager.DefaultItems = defaultItems; //重新赋值
            $UIManager.Render();//重新渲染

            if (vals && defaultItems.indexOf(vals) != -1) {
                $.MvcSheetUI.SetControlValue(dibm, vals, i);
            }
        }
    }
}

//设置语言
function setLanguage() {

    var languagesMap = {"en_us": "EN_US", "zh_cn": "ZH_CN", "zh_tw": "ZH_TW"};
    var languVal = $.MvcSheetUI.SheetInfo.Language;

    $.MvcSheetUI.SetControlValue("CHANGELANG", languagesMap[languVal]);
    if(!$.MvcSheetUI.GetControlValue("CHANGELANG")){
        $.MvcSheetUI.SetControlValue("CHANGELANG", languagesMap["zh_cn"]);
    }

}


var cnpjValOrig = null;

// 企业经营信息
function loadBussta() {

    var vals = $.MvcSheetUI.GetControlValue("YCNPJ");

    if (cnpjValOrig == vals) {
        return false;
    } else {
        cnpjValOrig = vals;
    }

    var gridNew = $.MvcSheetUI.GetElement("BUSSTACHG").SheetGridView();

    if (vals && vals.trim()) {
        console.log("loadBussta...");

        var param = '{"YCNPJ":"' + vals + '"}';
        $.ajax({
            url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
            data: {
                "schemaCode": "ZMANSTATE",
                "queryCode": "queryZMANSTATE",
                "FilterStr": param,
                "PageIndex": 1,
                "PageSize": 20
            },
            dataType: "json",
            async: true,
            success: function (data) {
                if (data) {
                    gridNew._Clear();
                    if (data.Total && data.Total > 0) {
                        for (var i = 0; i < data.Total; i++) {
                            gridNew._AddRow();

                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YEARS", data.Rows[i].YEAR, i + 1);//年份
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YZCZE", (data.Rows[i].ZCZE *10000), i + 1);//资产总额
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YQZZE", (data.Rows[i].FZZE*10000), i + 1);//负债总额
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YYSZE", (data.Rows[i].YYZSR *10000), i + 1);//营业总收入
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YJLR", (data.Rows[i].JLR *10000), i + 1);//净利润
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.ZCFZL", data.Rows[i].ZCFZL, i + 1);//资产负债率
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.JLRL", data.Rows[i].JLRL, i + 1);//净利润率
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.ZZCZZL", data.Rows[i].ZZCZZL, i + 1);//总资产周转率
                        }
                    }
                    gridNew._AddRow();
                }

            }
        });

    } else {
        gridNew._Clear();
        gridNew._AddRow();
    }

    return false;
}


function queryXsdb() {
    var loginCode = $.MvcSheetUI.GetControlValue("THISlOGINNAME");

    if (!loginCode) return false;

    var param = '{"ADYHM":"' + loginCode + '"}';
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
        data: {
            "schemaCode": "ZXSDBX3",
            "queryCode": "queryXSDBsByLoginCode",
            "FilterStr": param,
            "PageIndex": 1,
            "PageSize": 20
        },
        dataType: "json",
        async: true,
        success: function (data) {
            if (data) {
                if (data.Total && data.Total > 0) {
                    $.MvcSheetUI.SetControlValue("REP_0_XS", data.Rows[0].MC);
                    $.MvcSheetUI.SetControlValue("REP_0", data.Rows[0].BM);
                    queryTjz();
                }
            }
        }
    });
}

function queryTjz() {
    var xsdbbm = $.MvcSheetUI.GetControlValue("REP_0");


    if (!xsdbbm || $.MvcSheetUI.GetControlValue("TSCCOD_0_XS")) return false;

    var param = '{"BM":"' + xsdbbm + '"}';
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
        data: {
            "schemaCode": "ZKHTJZX31",
            "queryCode": "ZKHTJZX31",
            "FilterStr": param,
            "PageIndex": 1,
            "PageSize": 20
        },
        dataType: "json",
        async: true,
        success: function (data) {
            if (data) {
                if (data.Total && data.Total > 0) {
                    $.MvcSheetUI.SetControlValue("TSCCOD_0_XS", data.Rows[0].KHTJZ1);
                    $.MvcSheetUI.SetControlValue("TSCCOD_1_XS", data.Rows[0].KHTJZ2);
                    $.MvcSheetUI.SetControlValue("TSCCOD_2_XS", data.Rows[0].KHTJZ3);
                    $.MvcSheetUI.SetControlValue("TSCCOD_3_XS", data.Rows[0].KHTJZ4);
                    $.MvcSheetUI.SetControlValue("TSCCOD_4_XS", data.Rows[0].KHTJZ5);
                    $.MvcSheetUI.SetControlValue("TSCCOD_0", data.Rows[0].KHTJZBM1);
                    $.MvcSheetUI.SetControlValue("TSCCOD_1", data.Rows[0].KHTJZBM2);
                    $.MvcSheetUI.SetControlValue("TSCCOD_2", data.Rows[0].KHTJZBM3);
                    $.MvcSheetUI.SetControlValue("TSCCOD_3", data.Rows[0].KHTJZBM4);
                    $.MvcSheetUI.SetControlValue("TSCCOD_4", data.Rows[0].KHTJZBM5);
                }
            }
        }
    });
}




// 客户地址编码自增，最多26 个字母，且表单初始化row 为0；
function insrBPAADD() {
    var $tb = $.MvcSheetUI.GetElement("BPADDRESSCHG").SheetGridView();
    if ($tb) {
        var rowIndex = $tb.RowCount;
        var vals = $.MvcSheetUI.GetControlValue("BPADDRESSCHG.BPAADD", rowIndex);
        if (!vals) {
            $.MvcSheetUI.SetControlValue("BPADDRESSCHG.BPAADD", String.fromCharCode((64 + rowIndex)), rowIndex);
        }

        if(rowIndex ==1){
            checboxOnly( $.MvcSheetUI.GetElement("BPADDRESSCHG.BPAADDFLG_XS", rowIndex));
            $.MvcSheetUI.SetControlValue("BPADDRESSCHG.YSHFLG_XS",true,rowIndex);
            $.MvcSheetUI.SetControlValue("BPADDRESSCHG.YDEFSHFLG_XS",true,rowIndex)
            isReceivingAdd_Chcekbox($.MvcSheetUI.GetElement("BPADDRESSCHG.YSHFLG_XS",rowIndex));
            checboxOnlyDefshflg($.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG_XS",rowIndex));
        }
    }
}

function addOnRenderedEvent() {
    var $tb = $.MvcSheetUI.GetElement("CONTACTCHG").SheetGridView();
    if ($tb) {
        var rowIndex = $tb.RowCount;

        if(rowIndex ==1){
            checboxOnly($.MvcSheetUI.GetElement("CONTACTCHG.CNTFLG_XS",  rowIndex));
        }
    }
}



function getYbpcbusage() {
    var year0 = new Date().getTime();
    var yregstartd = $.MvcSheetUI.GetControlValue("YREGSTARTD");
    if (yregstartd) {
        var year1 = new Date(yregstartd).getTime();
        var year3 = 0;
        if (year0 > year1) {
            var year3 = (year0 - year1) / (3600 * 1000 * 24 * 365);
            if (year3)
                year3 = year3.toFixed(1);
        }


        $.MvcSheetUI.SetControlValue("YBPCBUSAGE", year3);

    }
}


// 监听 /F7 118/ 回车 13
function inputKeypress() {

    if ($.MvcSheetUI.SheetInfo.ActivityCode != "Activity2") {
        return false;
    }

    // console.log(11);
    $('input[data-popupwindow="PopupWindow"]').parent().bind('keyup', function (event) {

        if (event.keyCode == "13") {
            event.preventDefault();
            //回车执行查询
            var $that = $(event.currentTarget);
            $that.find("a").click();

        }
    });
}


function activeAdds(){
    var  $adds = $.MvcSheetUI.GetElement("BPADDRESSCHG").SheetComment();
    if($adds.RowCount ==0)
        $adds._AddRow();
    var  $adds1 = $.MvcSheetUI.GetElement("CONTACTCHG").SheetComment();
    if($adds1.RowCount ==0){
        $adds1._AddRow();
        $adds1._AddRow();
        $.MvcSheetUI.SetControlValue("CONTACTCHG.CNTFNC",6,1);
        $.MvcSheetUI.SetControlValue("CONTACTCHG.CNTFNC",2,2);
    }



}

//依赖清空
function dependenceClean(fiel1,fiel2){
    try {
        $.MvcSheetUI.SetControlValue(fiel1,"");
        $.MvcSheetUI.SetControlValue(fiel2,"");
    }catch(e){
        console.log(e);
    }
}

// 隐藏贸易类型
// {CUR} != 'CNY' && {CUR}!='HKD'
function hideMylx(){
    var  comment = $.MvcSheetUI.GetControlValue("CUR");
    if(comment != 'CNY' && comment!='HKD'){
        $.MvcSheetUI.GetElement("YTRADTPY_XS").parent().show();

    }else{
        $.MvcSheetUI.GetElement("YTRADTPY_XS").parent().hide();
        $.MvcSheetUI.SetControlValue("YTRADTPY_XS","");
        $.MvcSheetUI.SetControlValue("YTRADTPY","");
        $.MvcSheetUI.SetControlValue("YTRADTPYDES","");
    }
}

//上一次验证不通过的
var cusomerName1016 = new Array();

var isExistCustomerFlag = 1;
function isExistCustomer($this) {

    if (isExistCustomerFlag ==1){
        isExistCustomerFlag = 2;
    }else {
        return  false;
    }

    var thisVal = $this.SheetComment().GetValue();

    thisVal = DBC2SBC(thisVal);

    var valLenght = thisVal ? thisVal.length : 0;

    if (valLenght && (thisVal = thisVal.trim())) {
        if (cusomerName1016.indexOf(thisVal) != -1) {
            $this.SheetComment().SetValue("");
            alert("已存在相同客户名称：" + thisVal);

        }else{
            //查询改名字是否已存在
            var param = '{"KHMCALL":"' + thisVal + '"}';
            $.ajax({
                url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
                data: {
                    "schemaCode": "KHYJD",
                    "queryCode": "KHYJDALL",
                    "FilterStr": param,
                    "PageIndex": 1,
                    "PageSize": 2
                },
                dataType: "json",
                async: true,
                success: function (data) {

                    if (data) {
                        if (data.Total && data.Total > 0) {
                            cusomerName1016[cusomerName1016.length] = thisVal;
                            $this.SheetComment().SetValue("");
                            alert("已存在相同客户名称：" + thisVal);
                        }else{
                            $this.SheetComment().SetValue(thisVal);
                        }
                    }
                    isExistCustomerFlag == 1;
                }
            });
        }

    }
    isExistCustomerFlag == 1;
    return false;
}


function DBC2SBC(str)
{
    var result="";
    for(var i=0;i<str.length;i++)
    {
        code = str.charCodeAt(i);//获取当前字符的unicode编码
        if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
        {
            var d=str.charCodeAt(i)-65248;
            result += String.fromCharCode(d);//把全角字符的unicode编码转换为对应半角字符的unicode码
        }
        else if (code == 12288)//空格
        {
            var d=str.charCodeAt(i)-12288+32;
            result += String.fromCharCode(d);
        }
        else
        {
            result += str.charAt(i);
        }
    }
    return result;
}